<template>
  <el-dialog
    :title="title"
    v-model="d.isVisble"
    custom-class="addPatient-container"
    :close-on-click-modal="false"
    @closed="closed"
  >
    <el-form
      v-if="!d.id"
      ref="formRef"
      :model="hospitalForm"
      label-position="left"
    >
      <el-row :gutter="50">
        <el-col :span="20">
          <el-form-item prop="name" label="院方唯一标识" label-width="100px">
            <el-input
              v-model.trim="hospitalForm.id"
              placeholder="请输入，确定后点击查询"
            ></el-input>
          </el-form-item>
        </el-col>

        <!--        <el-col :span="4">-->
        <el-form-item>
          <el-button type="primary" @click="searchHospitalData">查询</el-button>
        </el-form-item>
        <!--        </el-col>-->
      </el-row>
    </el-form>
    <el-form ref="formRef" :rules="rules" :model="d.form" label-position="top">
      <el-row :gutter="50">
        <el-col :span="8">
          <el-form-item prop="name" label="患者姓名" label-width="80px">
            <el-input
              v-model.trim="d.form.name"
              placeholder="最多三十个字"
              @change="queryPatientChange"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="diagnosisNo" label="诊疗卡号" label-width="80px">
            <el-input
              v-model="d.form.diagnosisNo"
              placeholder="请填写诊疗卡号"
              @change="queryPatientChange"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="phone" label="电话号码" label-width="80px">
            <el-input
              v-model="d.form.phone"
              placeholder="电话号码为11位数字"
              @change="queryPatientChange"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="sex" label="性别" label-width="80px">
            <el-select v-model="d.form.sex" style="width: 100%">
              <el-option
                v-for="item in sexOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="birthday" label="生日" label-width="80px">
            <el-date-picker
              v-model="d.form.birthday"
              style="width: 100%"
              placeholder="请选择生日"
              :disabledDate="disabledDate"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="cardNo" label="身份证号" label-width="80px">
            <el-input
              v-model="d.form.cardNo"
              placeholder="请填写身份证号"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="nation" label="民族" label-width="80px">
            <el-input
              v-model="d.form.nation"
              placeholder="请填写民族"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="regionName" label="住址" label-width="80px">
            <area-cascader
              v-model="d.form.city"
              v-model:area-all="d.form.regionName"
              v-model:city="d.form.city"
              v-model:district="d.form.district"
              v-model:province="d.form.province"
            ></area-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="address" label="详细地址" label-width="80px">
            <el-input
              v-model="d.form.address"
              placeholder="请填写住址,最多30字"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="email" label="电子邮箱" label-width="80px">
            <el-input
              v-model="d.form.email"
              placeholder="请填写电子邮箱"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            prop="allergicDrugs"
            label="过敏药物"
            label-width="80px"
          >
            <el-input
              v-model="d.form.allergicDrugs"
              placeholder="请输入过敏的药物"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="allergicFood" label="过敏食物" label-width="80px">
            <el-input
              v-model="d.form.allergicFood"
              placeholder="请输入过敏的食物"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider v-if="!isPatient"></el-divider>
      <el-row :gutter="50">
        <template v-if="!isPatient">
          <el-col :span="8">
            <el-form-item prop="departmentId" label="科室" label-width="80px">
              <xm-remote-select
                ref="departmentRef"
                v-model="d.form.departmentId"
                v-model:label="d.form.departmentName"
                :defaults="d.defaults"
                :itemList="dt.itemList"
                @loadData="dtLoad"
              ></xm-remote-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="type" label="看病类型" label-width="80px">
              <el-select
                v-model="d.form.type"
                style="width: 100%"
                @change="() => (d.form.outpatientNo = null)"
              >
                <el-option
                  v-for="item in types"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              prop="outpatientNo"
              v-if="d.form.type !== null"
              :label="d.form.type === 1 ? '住院号' : '门诊号'"
              label-width="80px"
            >
              <el-input
                v-model="d.form.outpatientNo"
                :placeholder="d.form.type === 1 ? '请输入住院号' : '请输入门诊号'"
              ></el-input>
            </el-form-item>
          </el-col>
          <template  v-if="d.form.type === 1">
            <el-col :span="8">
              <el-form-item
                prop="roomNo"
                label="房号"
                label-width="80px"
              >
                <el-input
                  v-model.number="d.form.roomNo"
                  placeholder="请输入房间号"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                prop="bedNo"
                label="床号"
                label-width="80px"
              >
                <el-input
                  v-model.number="d.form.bedNo"
                  placeholder="请输入床号"
                ></el-input>
              </el-form-item>
            </el-col>
          </template>
        </template>
        <el-col :span="8">
          <el-form-item
            prop="attendingDoctor"
            label="主治医生"
            label-width="80px"
          >
            <el-input
              v-model.number="d.form.attendingDoctor"
              placeholder="请输入主治医生"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            prop="registrationNo"
            label="登记号"
            label-width="80px"
          >
            <el-input
              v-model.number="d.form.registrationNo"
              placeholder="请输入登记号"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="d.isVisble = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </div>
    </template>
  </el-dialog>
  <node-table
    title="系统检测到有多份患者资料与您相关，请选择一份患者资料进行导入，或关闭弹窗新增患者"
    listType="hasCancal"
    :list="d.dataList"
    v-model="d.isShowNode"
    @nodeChage="selectClick"
  ></node-table>
</template>
<script>
  import { reactive, ref } from 'vue' // , nextTick
  import { merge } from 'lodash-es'
  import { isIDNumber } from '@/utils/validate.js' // validator
  import areaCascader from '@/components/AreaCascader'
  import {
    patientInfo,
    save,
    queryPatient,
    modify,
    getHospitalData,
  } from '@/api/modules/patient' // , modify
  import moment from 'moment'
  import common from '@/utils/common'
  import XmRemoteSelect from 'XMC/XmRemoteSelect'
  import NodeTable from '@/components/NodeTable'
  import { useStore } from 'vuex'
  import { computed } from '@vue/reactivity'
  export default {
    name: 'addPatient',
    props: {
      title: String,
      modelValue: Boolean,
      id: Number,
      isPatient: Boolean, // 是否为修改患者信息
      type: Number, // type 患者类型 0 门诊 1 住院 2 未有
    },
    components: { areaCascader, XmRemoteSelect, NodeTable },
    emits: ['success', 'update:modelValue'],
    data() {
      return {
        sexOptions: [
          { value: 1, label: '男' },
          { value: 0, label: '女' },
        ],
        treatmentOptions: [
          { value: 1, label: '首诊' },
          { value: 0, label: '复诊' },
        ],
        types: [
          { value: 0, label: '门诊' },
          { value: 1, label: '住院' },
        ],
      }
    },
    setup(props, context) {
      const rules = {
        name: [
          { required: true, message: '请输入患者姓名', trigger: 'blur' },
          {
            min: 2,
            max: 30,
            message: '最少两个字，最多三十个字',
            trigger: 'blur',
          },
        ],
        birthday: [{ required: true, message: '请选择生日', trigger: 'blur' }],
        sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        phone: [
          {
            required: true,
            min: 11,
            max: 11,
            message: '电话号码为11位数字',
            trigger: 'blur',
          },
        ],
        cardNo: [
          {
            required: false,
            validator: isIDNumber,
            message: '请输入正确的身份证信息',
            trigger: 'blur',
          },
        ],
        nation: [{ min: 1, message: '请输入民族信息', trigger: 'blur' }],
        regionName: [
          {
            required:
              process.env.VUE_APP_MUST_ADDRESS === 'true' ? true : false,
            message: '请选择住址',
            trigger: 'change',
          },
        ],
        address: [
          {
            required:
              process.env.VUE_APP_MUST_ADDRESS === 'true' ? true : false,
            message: '请填写住址',
            trigger: 'change',
          },
          {
            max: 30,
            message: '请填写30字以内的住址',
            trigger: 'change',
          },
        ],
        email: [{ message: '请填写正确的电子邮件', trigger: 'blur' }],
        departmentId: [
          { required: true, message: '请填写科室', trigger: 'change' },
        ],
        type: [
          { required: true, message: '请选择看病类型', trigger: 'change' },
        ],
        diagnosisNo: [
          { required: true, message: '请填写诊疗卡号', trigger: 'blur' },
        ],
        outpatientNo: [
          {
            required: true,
            message: props.type === 1 ? '请填写住院号' : '请填写门诊号',
            trigger: 'blur',
          },
        ],
        attendingDoctor: [
          {
            required: true,
            message: '请填写主治医生',
            trigger: 'blur',
          },
        ],
        registrationNo: [
          {
            required: true,
            message: '请填写登记号',
            trigger: 'blur',
          },
        ],
      }

      const getForm = function () {
        return {
          name: null,
          birthday: null,
          sex: null,
          phone: null,
          cardNo: null,
          nation: null,
          regionName: null,
          city: null, // 区id
          district: null, // 市id
          province: null, // 省id
          email: null,
          departmentId: null,
          departmentName: null,
          treatmentType: null,
          diagnosisNo: null, // 诊疗号
          outpatientNo: null, // 门诊号
          allergicDrugs: null, // 过敏药物
          allergicFood: null, // 过敏食物
          roomNo: null,
          bedNo: null,
          address: null,
          type: null, // 看病类型
          attendingDoctor: null, // 主治医生
          registrationNo: null, // 登记号
          // height: null,
          // weight: null,
        }
      }
      // 初始化
      const d = reactive({
        form: getForm(),
        defaults: null,
        isVisble: false,
        type: null,
        id: null,
        historicalVisitId: null,
        isShowNode: false,
        dataList: null,
        isSaving: false,
        quickReceptionType: null,
      })
      const loadData = async function (id, historicalVisitId) {
        let res = await patientInfo({ id, historicalVisitId })
        if (res.data) {
          d.form = res.data
          if (d.form.departmentName && d.form.departmentId) {
            d.defaults = {
              value: d.form.departmentId,
              label: d.form.departmentName,
            }
          }
        }
      }
      const closed = function () {
        d.form = getForm()
        d.isVisble = false
        d.defaults = null
        d.id = null
        d.historicalVisitId = null
        d.isSaving = false
        d.quickReceptionType = null
        formRef.value.resetFields()
        hospitalForm.value.id = null
      }
      const toSave = async function (form) {
        common.XmLoading(true)
        form['birthday'] = moment(form.birthday).format('YYYY-MM-DD HH:mm:ss')
        if (d.form.type === 3) {
          const tmp = { ...form, id: d.id }
          if (d.quickReceptionType)
            tmp['quickReceptionType'] = d.quickReceptionType
          await modify(tmp)
            .then((res) => {
              // TODO 提示成功并关闭
              common.XmLoading()
              d.isVisble = false
              context.emit('success', { pid: d.id, res })
            })
            .catch(() => {
              common.XmLoading()
              return
            })
        } else {
          const tmp = { ...form, id: d.id }
          await save({
            ...tmp,
            historicalVisitId: d.historicalVisitId,
            quickReceptionType: d.quickReceptionType,
          })
            .then((res) => {
              // TODO 提示成功并关闭
              common.XmLoading()
              d.isVisble = false
              context.emit('success', { pid: d.id, res })
            })
            .catch(() => {
              // TODO 报错
              common.XmLoading()
              return
            })
        }
      }
      // 表单方法
      const formRef = ref(null)
      const onSubmit = function () {
        d.isSaving = true
        formRef.value.validate((valid) => {
          if (valid) {
            toSave(d.form)
          } else {
            return false
          }
        })
      }
      const dt = reactive({ itemList: [] })
      const store = useStore()
      const dtLoad = async function (cb) {
        dt.itemList = await store.dispatch('presetData/getDepartmentList')
        cb()
      }

      const queryPatientChange = function () {
        if (d.form.type === 3) return
        const { name, diagnosisNo, phone } = d.form
        let i = 0
        if (name) i += 1
        if (diagnosisNo) i += 1
        if (phone) i += 1
        if (i >= 3) {
          // 延时 为了让确定按钮先改状态
          setTimeout(async () => {
            // 如果已经保存 就不需要加载患者了
            if (d.isSaving) return
            const res = await queryPatient({ name, diagnosisNo, phone })
            // 如果已经保存 就不需要加载环境了
            // if (d.isSaving) return
            if (res.data.length >= 1) {
              common.XmAlert('查询到相似患者，是否加载', () => {
                d.isShowNode = true
                d.dataList = res.data
              })
            }
          }, 200)
        }
      }

      const selectClick = function (val) {
        d.isShowNode = false
        d.form = merge(getForm(), val)
        d.defaults = {
          value: d.form.departmentId,
          label: d.form.departmentName,
        }
      }
      const departmentRef = ref(null)
      const init = async function (config) {
        console.log('config =' + JSON.stringify(config))
        if (config.quickReceptionType)
          d.quickReceptionType = config.quickReceptionType
        if (config.obj) {
          // 快速建档 将其他信息专为
          d.form = config.obj
          d.form.flowDetailedId = d.form.id
          delete d.form.id
        } else if (config.id) {
          loadData(config.id, config.historicalVisitId)
        }

        d.isVisble = config.isVisble ? config.isVisble : true
        d.id = config.id
        d.historicalVisitId = config.historicalVisitId
        if (config.type !== null && typeof config.type !== 'undefined')
          d.form.type = config.type
        if (config.edit) {
          console.log('修改就诊科室')
          // await nextTick()
          // departmentShow.value.focus()
        }
      }

      // 时间选择器 TODO 待合并
      const disabledDate = function (time) {
        return time.getTime() > Date.now()
      }

      const hospitalForm = ref({ id: null })
      // 查询院方数据
      const searchHospitalData = () => {
        const { id } = hospitalForm.value
        common.XmLoading(true)
        getHospitalData({ cardNo: id })
          .then((res) => {
            common.XmLoading(false)

            // 是否删掉 province city  district
            delete res.data.province
            delete res.data.city
            delete res.data.district
            d.form = { ...d.form, ...res.data }
            common.XmMessage(0, '导入成功')
          })
          .catch((err) => {
            common.XmLoading(false)
            common.XmMessage(0, err.message || '查询人员发生错误')
            console.log('getHospitalData err =' + JSON.stringify())
          })
      }
      return {
        d,
        rules,
        loadData,
        onSubmit,
        formRef,
        dtLoad,
        dt,
        init,
        disabledDate,
        queryPatientChange,
        departmentRef,
        closed,
        selectClick,
        searchHospitalData,
        hospitalForm,
      }
    }, // props, context
  }
</script>
<style lang="scss">
  .el-dialog.addPatient-container {
    min-width: 1000px;
    .el-dialog__body {
      padding: 0px 50px 30px 50px;
      .el-form {
        width: 100%;
        height: 100%;
        //.el-form-item {
        //  // background-color: red !important;
        //  //flex-direction: column;
        //  //line-height: 30px;
        //  margin-bottom: 11px;
        //  //width: 100%;
        //  font-size: 12px;
        //  .el-form-item__label {
        //    line-height: 30px;
        //    //text-align: left;
        //  }
        //}

        .el-divider--horizontal {
          margin: 12px 0;
        }
      }
    }
  }
</style>
